import 'package:cached_network_image/cached_network_image.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../network/Api.dart';

class SeachGroup extends StatefulWidget {
  const SeachGroup({Key? key}) : super(key: key);

  @override
  State<SeachGroup> createState() => _SeachGroupState();
}

class _SeachGroupState extends State<SeachGroup> {
  final GlobalKey _formKey = GlobalKey<FormState>();
  final TextEditingController _messController = TextEditingController();
  final FocusNode _focusNode = FocusNode();
  bool canSend = false;
  bool send = false;
  late String centext;
  List<String> members=[];
  final ScrollController scrollController = ScrollController();
  List<dynamic>  list = [];

  Map _userInfo = {};

  void validateInput(String test) {
    setState(() {
      canSend = test.isNotEmpty;
      centext = test;
    });
  }

  // 模糊查群信息
  _getUserinfo(String string) async {
     if (string.isEmpty) return;
    final res = await Api.getInstance().queryGroupInfo(string);
    final data = res['data'];
     if (data != null) {
       List listt = data;
       if (listt.isNotEmpty == true) {

         setState(() {
           send = true;
           list.clear();
           list.addAll(listt);
         });
       }
     } else {
       if (kDebugMode) {
         print('------通讯录异常记录---------------'+res['msg']);
       }

     }
  }

  // 添加环信用户信息
  _addUserinfo(String string,String strin, int index) async {
     if (string.isEmpty) return;
    final res = await Api.getInstance().addGroupMember(string,strin);
    final data = res['data'];
    if (res["code"] == 0) {
      setState(() {
        list.removeAt(index);
        send = false;
      });
    } else {
      if (kDebugMode) {
        print('------获取用户异常---------------' + res['msg']);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: [
          const SizedBox(
            height: 20,
          ),
          Flexible(
            child: Row(
              children: [
                Form(
                    key: _formKey,
                    child: SizedBox(
                      width: 300,
                      height: 40,
                      child: TextFormField(
                          autofocus: false,
                          maxLines: 3,
                          controller: _messController,
                          focusNode: _focusNode,
                          onChanged: validateInput,
                          keyboardType: TextInputType.text,
                          decoration: const InputDecoration(
                            isCollapsed: true,
                            fillColor: Color(0xffF1F3FB),
                            filled: true,
                            hintText: "请输入群ID/群名",
                            prefixIcon: Icon(
                              Icons.search,
                              size: 20,
                              color: Colors.grey,
                            ),
                            contentPadding: EdgeInsets.only(left: 5, top: 10),
                            enabledBorder: OutlineInputBorder(
                              /*边角*/
                              borderRadius: BorderRadius.all(
                                Radius.circular(30), //边角为30
                              ),
                              borderSide: BorderSide(
                                color: Colors.white54, //边线颜色为黄色
                                width: 1, //边线宽度为2
                              ),
                            ),
                            focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.all(
                                  Radius.circular(30), //边角为30
                                ),
                                borderSide: BorderSide(
                                  color: Colors.white54, //边框颜色为绿色
                                  width: 1, //宽度为5
                                )),
                          )),
                    )),
                Offstage(
                  offstage: !canSend,
                  child: InkWell(
                    onTap: () {
                      if (canSend) {
                        _getUserinfo(centext);
                      }
                    },
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 8, vertical: 8),
                      decoration: ShapeDecoration(
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(5)),
                          color: ThemeColor.mainColor),
                      child: const Text(
                        '搜索',
                        style: TextStyle(color: Colors.white, fontSize: 14),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
         Flexible(child:  Container(
           padding: const EdgeInsets.only(left: 14,right: 14,top: 21,bottom: 21),
           child: ListView.builder(
             controller: scrollController,
             itemBuilder: (_, index) {
               if (list?.isNotEmpty==true) {
                 return Container(
                   margin: const EdgeInsets.only(top: 10),
                   padding: const EdgeInsets.only(
                       left: 16, top: 11, bottom: 10, right: 16),
                   child: Row(
                     mainAxisAlignment: MainAxisAlignment.spaceAround,
                     children: [
                       Flexible(
                           child: Row(
                             children: [
                               Container(
                                 padding: const EdgeInsets.only(left: 15),
                                 child: ClipRRect(
                                   borderRadius: BorderRadius.circular(5),
                                   child: CachedNetworkImage(
                                     imageUrl: Provider.fixAvatar(
                                         list[index]['groupUrl'] ?? ""),
                                     width: 40,
                                     height: 40,
                                     fit: BoxFit.fill,
                                   ),
                                 ),
                               ),
                               const SizedBox(
                                 width: 12,
                               ),
                               Text(
                                 list[index]['groupName'] ?? "",
                                 style: const TextStyle(
                                     fontSize: 16,
                                     color: Colors.black,
                                     fontWeight: FontWeight.normal),
                               ),
                               const Expanded(child: Text("")),
                             ],
                           )),
                       InkWell(
                         onTap: () {
                           if (list[index]['groupId'].toString().isNotEmpty) {
                             members.clear();
                             members.add(Provider.userEaseName);
                             _addUserinfo(Provider.userEaseName,list[index]['groupId'].toString(),index);
                           }
                         },
                         child: Container(
                           padding: const EdgeInsets.symmetric(
                               horizontal: 8, vertical: 8),
                           decoration: ShapeDecoration(
                               shape: RoundedRectangleBorder(
                                   borderRadius: BorderRadius.circular(5)),
                               color: ThemeColor.mainColor),
                           child: const Text(
                             '添加',
                             style: TextStyle(color: Colors.white, fontSize: 14),
                           ),
                         ),
                       ),
                     ],
                   ),
                 );
               } else {
                 return Container();
               }
             },
             itemCount: list?.length,
           ),
         )),

          // Offstage(
          //   offstage: !send,
          //   child: Container(
          //     margin: const EdgeInsets.only(top: 10),
          //     padding: const EdgeInsets.only(
          //         left: 16, top: 11, bottom: 10, right: 16),
          //     child: Row(
          //       mainAxisAlignment: MainAxisAlignment.spaceAround,
          //       children: [
          //         Flexible(
          //             child: Row(
          //           children: [
          //             Container(
          //               padding: const EdgeInsets.only(left: 15),
          //               child: ClipRRect(
          //                 borderRadius: BorderRadius.circular(5),
          //                 child: CachedNetworkImage(
          //                   imageUrl: Provider.fixAvatar(
          //                       _userInfo['profilePhoto'] ?? ""),
          //                   width: 40,
          //                   height: 40,
          //                   fit: BoxFit.fill,
          //                 ),
          //               ),
          //             ),
          //             const SizedBox(
          //               width: 12,
          //             ),
          //             Text(
          //               _userInfo['nickName'] ?? "",
          //               style: const TextStyle(
          //                   fontSize: 16,
          //                   color: Colors.black,
          //                   fontWeight: FontWeight.normal),
          //             ),
          //             const Expanded(child: Text("")),
          //           ],
          //         )),
          //         InkWell(
          //           onTap: () {
          //             if (_userInfo['groupId'].toString().isNotEmpty) {
          //               members.clear();
          //               members.add(Provider.userEaseName);
          //               _addUserinfo(members,_userInfo['groupId'].toString());
          //             }
          //           },
          //           child: Container(
          //             padding: const EdgeInsets.symmetric(
          //                 horizontal: 8, vertical: 8),
          //             decoration: ShapeDecoration(
          //                 shape: RoundedRectangleBorder(
          //                     borderRadius: BorderRadius.circular(5)),
          //                 color: ThemeColor.mainColor),
          //             child: const Text(
          //               '添加',
          //               style: TextStyle(color: Colors.white, fontSize: 14),
          //             ),
          //           ),
          //         ),
          //       ],
          //     ),
          //   ),
          // ),
        ],
      ),
    );
  }
}
